<template>
  <el-card>
    <h1 class="title">聊天室</h1>
    <div class="message-list">
      <div v-for="(msg, index) in messageList" :key="index">
        {{ msg }}
      </div>
    </div>
    <div class="message-box">
      <el-input v-model="message" :rows="4" type="textarea" />
      <el-button
        type="primary"
        class="btn"
        :disabled="!message"
        @click="sendMessage"
        >发送</el-button
      >
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { ref } from "vue";

defineOptions({
  name: "App",
});

const message = ref("");

// 1. 客户端连接上ws服务器
const ws = new WebSocket("ws://192.168.12.81:8080");

// 2. 客户端给服务器发送消息
const sendMessage = () => {
  ws.send(message.value);
  message.value = "";
};

// 3. 客户端接受服务器的消息
const messageList = ref<string[]>([]);

ws.onmessage = function (e) {
  const message = e.data;
  messageList.value.push(message);
};
</script>

<style scoped>
.title {
  margin: 0 0 20px 0;
  text-align: center;
}
.message-list {
  border: 1px solid #dcdfe6;
  height: 300px;
  margin-bottom: 10px;
  padding: 10px;
}
.message-box {
  position: relative;
}
.btn {
  position: absolute;
  right: 10px;
  bottom: 10px;
}
</style>
